#include "../head/mainwindow.h"
#include "ui_mainwindow.h"
#include <QtCore/QDir>
#include <QtQuick/QQuickView>
#include <QtQml/QQmlEngine>
#include <QtCharts>
#include <QtCharts/QChartView>
#include <QtCharts/QChart>
#include <QtCharts/QLegend>
#include <QtCharts/QPieSeries>
#include <QtCharts/QPieSlice>
#include <QtCore/QTime>
#include <QtWidgets/QGridLayout>
#include <QtCharts/QScatterSeries>
#include <QTextCodec>
#include <QTime>
//#include "../head/utils/antcpserver.h"

//extern anTcpServer server;
#include "../head/formtext.h"



QT_CHARTS_USE_NAMESPACE
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{

    ui->setupUi(this);
    qDebug()<<"1111111111111111 ";
    cf = new ConfigForm();
    rf = new RecordForm();
    pl = new PredictLineForm();
    radarForm = new RadarForm();
    hf_1 = new HistoryForm_1();
    hf_2 = new HistoryForm_2();
    hf = new HistoryForm();
    //ddms = new DdmsForm();
    df = new DemoudleForm();
    rf = new RecordForm();
    pl = new PredictLineForm();
    qDebug()<<"22222222222222 ";
    tempArray = NEW(mutiSignalDecode->DemodParam[0]->PreSignal_Len*6,double);

    //this->setWindowTitle("导向钻进管理系统DDMS");

    statusLow = new QLabel;
    ui->statusbar->addWidget(statusLow);
    statusSend = new QLabel;
    ui->statusbar->addWidget(statusSend);
    statusTcpIp = new QLabel;
    ui->statusbar->addWidget(statusTcpIp);


    //setCentralWidget(wpl);
    // console = new Console;
    // console->setEnabled(false);
    // setCentralWidget(radarForm);
    //ui->centralwidget->setStyleSheet("background-color: rgb(0, 0, 0);");
    ui->stackedWidget->insertWidget(0,radarForm);
    ui->stackedWidget->setCurrentIndex(0);
    //ui->plainTextEdit->setReadOnly(true);
    initActionsConnections();
    connect(cf, &ConfigForm::sendStatusMessage,this,&MainWindow::showStatusMessage);
    connect(mutiSerialControl, &MutiSerialControl::sendToDemoudle, this,&MainWindow::acceptMutiSerialMessage);
    //connect(&client_,&TcpClient::sendStatusMessage,this,&MainWindow::showStatusMessage);
    qDebug()<<"333333333333 ";
    //connect(demoduleUtil, &DemoduleUtil::sendDeCodeData, this,&MainWindow::acceptDecodeData);
    //connect(&server, &anTcpServer::sendDataToMain,this,&MainWindow::acceptMessageFromNetwork);
    showStatusMessage("断开", 0);
    showStatusMessage("断开", 1);
    showStatusMessage("断开", 3);
    //timerIcon = new QTimer(this);
    trayIcon = new QSystemTrayIcon(this);
    connect(timerIcon,&QTimer::timeout,this, [=](){
        QIcon icon1 ;
        if(mutiSerialControl->portStatus[0] == 0){
            if(mutiSerialControl->portStatus[2] == 0){ //portStatus[2] 交替闪烁;
              icon1 = QIcon(":/images/Red.png");
              mutiSerialControl->portStatus[2] = 1;
            }else{
                icon1 = QIcon();
                mutiSerialControl->portStatus[2] = 0;
            }
            trayIcon->setIcon(icon1);
            trayIcon->setToolTip("接收串口未连接");
        }else if(mutiSerialControl->portStatus[1] == 0){
            if(mutiSerialControl->portStatus[2] == 0){
              icon1 = QIcon(":/images/Yellow.png");
              mutiSerialControl->portStatus[2] = 1;
            }else{
                icon1 = QIcon();
                mutiSerialControl->portStatus[2] = 0;
            }
            trayIcon->setIcon(icon1);
            trayIcon->setToolTip("发送串口未连接");
        }else{
            icon1 = QIcon(":/images/logo.ico");
            trayIcon->setIcon(icon1);
            trayIcon->setToolTip(str_title);
            timerIcon->stop();
        }


    });

    timerIcon->start(1000);
    this->showMinimized();

    qDebug()<<"33333333333333333 ";
    QTimer *timerFileList = new QTimer();

    connect(timerFileList,&QTimer::timeout,this, [=](){
            QString path = mutiSignalDecode->baseUrl + "/source";
            QDir dir(path);
            if(!dir.exists())
            {
                return;
            }
            dir.setFilter(QDir::Files | QDir::NoSymLinks);
            QFileInfoList list = dir.entryInfoList();

            int file_count = list.count();
            if(file_count <= 0)
            {
                return;
            }

            QDateTime time2 = QDateTime::currentDateTime();

            for(int i=0; i<file_count; i++)
            {
                QFileInfo file_info = list.at(i);

                QString absolute_file_path = file_info.absoluteFilePath();
                QString file_name = file_info.fileName();
                QDateTime time1 = QDateTime::fromString(file_name.left(10), "yyyy-MM-dd");
                int days = time1.daysTo(time2);

                if(days > 7){
                    mutiSignalDecode->record_log("delete files "+file_name);
                    QFile file(absolute_file_path);
                    file.remove();
                }
               // qDebug()<<"File"<<i<<"====="<<file_info.fileName()<< "::::time2 - time1=" << days <<endl;

            }




    });
    timerFileList->start(1000*60*12);


}

void MainWindow::setComSerial(){
        QString fileName = QApplication::applicationDirPath() + "/conf/conf_comport.txt";
        QFile file(fileName);
        if(!file.open(QIODevice::ReadOnly)){
            qDebug()<<"打开失败";
        }

        QTextStream in(&file);
        QStringList  user_data;
        QString acceptPort,sendPort,tcpIp;
        int i = 0;

        while(!in.atEnd()){
            i++;
            QString line = in.readLine();
            user_data = line.split("=");
            if(i == 1){
                acceptPort = user_data[1];
            }else if(i == 2){
                sendPort  = user_data[1];
            }else if(i == 3){
                tcpIp  = user_data[1];
            }
        }
        file.close();

        int portNum = 0;
        if(acceptPort.length() > 1){
            QSerialPort::BaudRate baudRate = (QSerialPort::BaudRate)160000;
            QSerialPort::DataBits dataBits = (QSerialPort::DataBits)8;
            QSerialPort::StopBits stopBits = (QSerialPort::StopBits)1;
            QSerialPort::Parity checkBits = QSerialPort::NoParity;
            mutiSerialControl->serialPort[portNum]->setPortName(acceptPort);
            mutiSerialControl->serialPort[portNum]->setBaudRate(baudRate);
            mutiSerialControl->serialPort[portNum]->setDataBits(dataBits);
            mutiSerialControl->serialPort[portNum]->setStopBits(stopBits);
            mutiSerialControl->serialPort[portNum]->setParity(checkBits);

            if(mutiSerialControl->serialPort[portNum]->open(QIODevice::ReadOnly) == true){
                mutiSerialControl->start_Serial(portNum);
               // QMessageBox::information(this,"提示","串口连接成功");
               // ui->connectButton->setText("断开");
                showStatusMessage(acceptPort+"已连接",portNum);
                mutiSerialControl->portStatus[0] = 1;
            }else{
                QMessageBox::critical(this,"提示","接收串口连接"+acceptPort+"失败!");
                cf->show();
                return;
            }

        }

        if(sendPort.length() > 1){
            mutiSerialControl->sendDecDataPort->setPortName(sendPort);
            mutiSerialControl->sendDecDataPort->setBaudRate((QSerialPort::BaudRate)9600);
            mutiSerialControl->sendDecDataPort->setDataBits((QSerialPort::DataBits)8);
            mutiSerialControl->sendDecDataPort->setStopBits((QSerialPort::StopBits)1);
            mutiSerialControl->sendDecDataPort->setParity(QSerialPort::NoParity);
            if(mutiSerialControl->sendDecDataPort->open(QIODevice::ReadWrite) == true){
                mutiSerialControl->portStatus[1] = 1;
                showStatusMessage(sendPort+"已连接", 1);
            }
//            else{
//                QMessageBox::critical(this,"提示","发送串口连接"+sendPort+"失败!");
//                cf->show();
//                return;
//            }
        }
        if(mutiSerialControl->portStatus[0] == 1 && mutiSerialControl->portStatus[1] == 1)
        {
            QIcon icon1 = QIcon(":/images/logo.ico");
            trayIcon->setIcon(icon1);
            trayIcon->setToolTip(str_title);
            timerIcon->stop();
        }
//        else{
//            cf->show();
//        }

        if(tcpIp.length() > 1){
            QStringList  tcp_ip = tcpIp.split(":");
            emit cf->connectHost(tcp_ip[0], tcp_ip[1].toInt());
        }
}

void MainWindow::setWinTitle(QString title){
    str_title = title;

    this->setWindowTitle(title);

    //建立系统托盘图标
    QIcon icon = QIcon(":/images/logo.ico");
    setWindowIcon(icon);
    QIcon icon1 = QIcon(":/images/Red.png");

    trayIcon->setIcon(icon1);
    trayIcon->setToolTip("接收串口未连接");

    createActions();
    createTrayIcon();
    trayIcon->show();
    connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(iconActivated(QSystemTrayIcon::ActivationReason)));

}



void MainWindow::acceptMessageFromNetwork(QString datas){
    int hzType = 0;
   // QTime time;
    FILE *fp;
    QDateTime curDateTime = QDateTime::currentDateTime();
    double b10dec = 0.0;
    //time.start();


    if(mutiSignalDecode->save_source_data[hzType]>0){
        QString save_url = mutiSignalDecode->baseUrl + "/source/"+mutiSignalDecode->iniPortType[hzType]+curDateTime.toString(" yyyy-MM-dd hh")+".txt";
        QTextCodec *code = QTextCodec::codecForName("gb2312");
        std::string stdStr = code->fromUnicode(save_url).data();
        char const* save_url_ = stdStr.c_str();
        fp = fopen(save_url_, "a+");
    }

  // QDataStream in(&datas,QIODevice::ReadOnly);
    //in.setFloatingPointPrecision(QDataStream::DoublePrecision);

    //in >> readArray;
    //memcpy(readArray,datas.data(),8000);

    QStringList t_list = datas.split(",");
    for (int i = 0; i < mutiSignalDecode->DemodParam[0]->PreSignal_Len; i++) {
        b10dec = QString(t_list[i]).toFloat();
        mutiSignalDecode->MudSigStand[hzType]->Pri[i] = b10dec;

        if(mutiSignalDecode->save_source_data[hzType]>0){
            fprintf(fp,"%.12f\n",b10dec);
        }
    }

    if(mutiSignalDecode->save_source_data[hzType]>0){
        fclose(fp);
    }
    mutiSignalDecode->demodule(hzType); //开始解调

    mutiSignalDecode->frame_counter++;
    if(!df->isHidden()){
        if(hzType == HIGH){
            df->drawHighWaveformPlot();
        }else{
            df->drawLowWaveformPlot();
        }
    }
    if(!hf_1->isHidden()){
        if(hzType == HIGH){
            hf_1->drawHighWaveformPlot();
        }else{
            hf_1->drawLowWaveformPlot();
        }
    }
    if(!hf_2->isHidden()){
        hf_2->drawWaveformPlot(hzType);
    }


//    double timeCounter = time.elapsed();
//    if(timeCounter > 700){ //数据解析与渲染时间>700窗口重新打开
//        if(!df->isHidden()){
//            df->close();
//            df = new DemoudleForm();
//            df->show();
//        }
//        if(!hf_1->isHidden()){
//            hf_1->close();
//            hf_1 = new HistoryForm_1();
//            hf_1->show();
//        }
//        if(!hf_2->isHidden()){
//            hf_2->close();
//            hf_2 = new HistoryForm_2();
//            hf_2->show();
//        }
//        //qDebug()<<"timerCounter===="<<timeCounter<<endl;
//        mutiSignalDecode->record_log("port::"+QString::number(hzType)+":::timerCounter===="+QString::number(timeCounter));
//    }
}

void MainWindow::acceptMutiSerialMessage(int hzType){

    QCoreApplication::processEvents();
    QTime time;
    FILE *fp;
    QDateTime curDateTime = QDateTime::currentDateTime();
    double b10dec = 0.0;
    int countAA = 0;
    time.start();

    for (int i = 0; i < mutiSignalDecode->DemodParam[0]->PreSignal_Len*6; i++) {
        tempArray[i] = mutiSerialControl->fifoReceiver1[hzType].Buf[mutiSerialControl->fifoReceiver1[hzType].nRp];

        if(mutiSerialControl->fifoReceiver1[hzType].nRp < mutiSignalDecode->DemodParam[0]->PreSignal_Len*6*10 - 1){
            mutiSerialControl->fifoReceiver1[hzType].nRp++;
        }else{
            mutiSerialControl->fifoReceiver1[hzType].nRp=0;
        }
    }

    QTextCodec *code = QTextCodec::codecForName("gb2312");
    if(mutiSignalDecode->save_source_data[LOW]>0){
        QString save_url = mutiSignalDecode->baseUrl + "/source/"+curDateTime.toString("yyyy-MM-dd hh")+".txt";

        std::string stdStr = code->fromUnicode(save_url).data();
        char const* save_url_ = stdStr.c_str();
        fp = fopen(save_url_, "a+");


    }

//    if(mutiSignalDecode->save_source_data[HIGH]>0){
//        QString save_url1 = mutiSignalDecode->baseUrl + "/source/"+mutiSignalDecode->iniPortType[HIGH]+curDateTime.toString(" yyyy-MM-dd hh")+".txt";
//        std::string stdStr1 = code->fromUnicode(save_url1).data();
//        char const* save_url_1 = stdStr1.c_str();
//        fp1 = fopen(save_url_1, "a+");
//    }

//    b10dec = ((double)(tempArray[i*6+2])*256.0 + (double)(tempArray[i*6+3])) / 65536.0 * 2.5 - 1.25;
//    b10dec = b10dec*mutiSignalDecode->ZoomIn[LOW];
//    mutiSignalDecode->MudSigStand[LOW]->Pri[i] = b10dec;

//    b10dec = ((double)(tempArray[i*6])*256.0 + (double)(tempArray[i*6+1])) / 65536.0 * 2.5 - 1.25;
//    b10dec = b10dec*mutiSignalDecode->ZoomIn[HIGH];
//    mutiSignalDecode->MudSigStand[HIGH]->Pri[i] = b10dec;

    for (int i = 0; i < mutiSignalDecode->DemodParam[0]->PreSignal_Len; i++) {
        b10dec = ((double)(tempArray[i*6])*256.0 + (double)(tempArray[i*6+1])) / 65536.0 * 2.5 - 1.25;
        b10dec = b10dec*mutiSignalDecode->ZoomIn[LOW];
        mutiSignalDecode->MudSigStand[LOW]->Pri[i] = b10dec;
        if(mutiSignalDecode->DemodParam[0]->Demodule_Mode == 153) { //!0x99 PSK_PSK;
            b10dec = ((double)(tempArray[i*6+2])*256.0 + (double)(tempArray[i*6+3])) / 65536.0 * 2.5 - 1.25;
            b10dec = b10dec*mutiSignalDecode->ZoomIn[HIGH];
            mutiSignalDecode->MudSigStand[HIGH]->Pri[i] = b10dec;
        }
        if(mutiSignalDecode->save_source_data[LOW]>0){
            for(int j=0;j<6;j++){
                int ss = tempArray[i*6+j];
                QString qs00 = QString("%1").arg(ss,2,16,QLatin1Char('0')).toUpper();
                std::string stdqs00 = qs00.toStdString();
                char const* saveqs00_ = stdqs00.c_str();
                fprintf(fp,"%s ",saveqs00_);
            }
            fprintf(fp,"\n");
        }
//        if(mutiSignalDecode->save_source_data[HIGH]>0){
//            fprintf(fp1,"%.12f\n",mutiSignalDecode->MudSigStand[HIGH]->Pri[i]);
//        }
        if(tempArray[i*6+4] == 245 && tempArray[i*6+5] == 245){  //F5 F5
            countAA++;
        }
    }

    if(mutiSignalDecode->save_source_data[LOW]>0){
        fclose(fp);
    }
//    if(mutiSignalDecode->save_source_data[HIGH]>0){
//        fclose(fp1);
//    }

    if(countAA != mutiSignalDecode->DemodParam[hzType]->PreSignal_Len){ // 重置串口信息;
        //qDebug() << "F5 F5 less than 1000..."<<endl;
        mutiSignalDecode->record_log("F5 F5 less than 1000...");
        mutiSerialControl->reset_Serial_Param(hzType);
    }

    mutiSerialControl->fifoReceiver1[hzType].nUsedCnt = mutiSerialControl->fifoReceiver1[hzType].nUsedCnt - mutiSignalDecode->DemodParam[0]->PreSignal_Len*6;

    //解调低频数据
    hzType = LOW;
    if(mutiSignalDecode->DemodParam[0]->Demodule_Mode == 152){ //!0x98 dpbsk DBPSK
        mutiSignalDecode->dbpsk_demodule(hzType); //开始解调
    }else{
        mutiSignalDecode->demodule(hzType); //开始解调
    }
    mutiSignalDecode->frame_counter++;
    if(!df->isHidden()){
        if(hzType == HIGH){
            df->drawHighWaveformPlot();
        }else{
            df->drawLowWaveformPlot();
        }
    }
    if(!hf_1->isHidden()){
        if(hzType == HIGH){
            hf_1->drawHighWaveformPlot();
        }else{
            hf_1->drawLowWaveformPlot();
        }
    }
    if(!hf_2->isHidden()){
        hf_2->drawWaveformPlot(hzType);
    }

    if(mutiSignalDecode->DemodParam[0]->Demodule_Mode == 153) { //!0x99 PSK_PSK;
    //解调高频数据
        hzType = HIGH;
        mutiSignalDecode->demodule(hzType); //开始解调
        if(!df->isHidden()){
            if(hzType == HIGH){
                df->drawHighWaveformPlot();
            }else{
                df->drawLowWaveformPlot();
            }
        }
        if(!hf_1->isHidden()){
            if(hzType == HIGH){
                hf_1->drawHighWaveformPlot();
            }else{
                hf_1->drawLowWaveformPlot();
            }
        }
        if(!hf_2->isHidden()){
            hf_2->drawWaveformPlot(hzType);
        }
    }
    double timeCounter = time.elapsed();
    if(timeCounter > 700){ //数据解析与渲染时间>700窗口重新打开
        if(!df->isHidden()){
            df->close();
            df = new DemoudleForm();
            df->show();
        }
        if(!hf_1->isHidden()){
            hf_1->close();
            hf_1 = new HistoryForm_1();
            hf_1->show();
        }
        if(!hf_2->isHidden()){
            hf_2->close();
            hf_2 = new HistoryForm_2();
            hf_2->show();
        }
        //qDebug()<<"timerCounter===="<<timeCounter<<endl;
        mutiSignalDecode->record_log("port::"+QString::number(hzType)+":::timerCounter===="+QString::number(timeCounter));
    }
}




void MainWindow::initActionsConnections()
{
    connect(ui->toolbarSetting, &QAction::triggered, [=](){
        if(cf != NULL){
            cf->close();
        }

        cf->show();
    });
    connect(ui->toolbarCaiyang, &QAction::triggered, [=](){
        if(hf_1 != NULL){
            hf_1->close();
        }
        hf_1 = new HistoryForm_1();
        hf_1->show();
    });

    connect(ui->toolbarXinzuotu, &QAction::triggered, [=](){
        //hf_2->show();

        if(df != NULL){
            df->close();
        }
        df = new DemoudleForm();
        df->show();
    });
    connect(ui->toolbarSheji, &QAction::triggered,    [=](){return;pl->show();});
    connect(ui->toolbarShigong, &QAction::triggered,  [=](){return;rf->show();});
    connect(ui->toolbarJietiao, &QAction::triggered,  [=](){return;radarForm->show();});
    connect(ui->toolbarHuifang, &QAction::triggered,  [=](){

        if(hf != NULL){
            hf->close();
        }
        hf = new HistoryForm();
        hf->pause_status = 0;
        hf->show();});
    connect(ui->toolbarClearData, &QAction::triggered,  [=](){
        //     ui->plainTextEdit->clear();
        radarForm->clearPlainText();
    });

    connect(ui->menuSetting, &QAction::triggered,[=](){
        if(cf != NULL){
            cf->close();
        }
        cf->show();
    });
    connect(ui->menuCaiyang, &QAction::triggered, [=](){
        if(hf_1 != NULL){
            hf_1->close();
        }
        hf_1 = new HistoryForm_1();hf_1->show();
    });

    connect(ui->menuXinzuo, &QAction::triggered,  [=](){
        //hf_2->show();
        return;
        if(df != NULL){
            df->close();
        }
        df = new DemoudleForm();
        df->show();
    });
    connect(ui->menuSheji, &QAction::triggered,   [=](){return;pl->show();});
    connect(ui->menuShigong, &QAction::triggered, [=](){return;rf->show();});
    connect(ui->menuJietiao, &QAction::triggered, [=](){return;radarForm->show();});
    connect(ui->menuHuifang, &QAction::triggered, [=](){hf->show();});
    connect(ui->menuMode, &QAction::triggered, [=](){
        FormText *ft = new FormText();
        ft->show();
    });


    connect(ui->toolbarHz1, &QAction::triggered,   [=](){

        ui->toolbarHz1->setIcon(QIcon(":/images/checked.png"));
        ui->toolbarHz2->setIcon(QIcon(":/images/check.png"));
        mutiSignalDecode->selhzType = 1;
        radarForm->setPlainText(1);
    });
    connect(ui->toolbarHz2, &QAction::triggered,   [=](){
        ui->toolbarHz2->setIcon(QIcon(":/images/checked.png"));
        ui->toolbarHz1->setIcon(QIcon(":/images/check.png"));
        mutiSignalDecode->selhzType = 0;
        radarForm->setPlainText(0);
    });

    connect(ui->menuExit, &QAction::triggered, [=](){ QApplication *app;app->exit(0);});

}


void MainWindow::handleError(QSerialPort::SerialPortError error){
    if (error == QSerialPort::ResourceError) {
        mutiSerialControl->serialPort[LOW]->close();
       //
        // demoduleUtil->record_log(serialUtil->serialPort->errorString());
        if(mutiSerialControl->portStatus[3] == 0){ //拔出串口会接收到多次消息，portStatus[3]多次信息只执行一次;
            QMessageBox::critical(this, tr("Critical Error"), mutiSerialControl->serialPort[LOW]->errorString());
            mutiSerialControl->portStatus[0] = 0;
            //  timerIcon->start(1000);
            mutiSerialControl->portStatus[3] = 1;
        }

        //cf->changeSerialStatus();
        mutiSignalDecode->record_log(mutiSerialControl->serialPort[LOW]->errorString());
        showStatusMessage("断开",LOW);

    }
}

void MainWindow::handleError1(QSerialPort::SerialPortError error){
    if (error == QSerialPort::ResourceError) {
        mutiSerialControl->serialPort[LOW]->close();
        //QMessageBox::critical(this, tr("Critical Error"), mutiSerialControl->serialPort[LOW]->errorString());
        // demoduleUtil->record_log(serialUtil->serialPort->errorString());
        //closeSerialPort();
        //cf->changeSerialStatus();

        mutiSignalDecode->record_log(mutiSerialControl->serialPort[LOW]->errorString());
        showStatusMessage("断开",LOW);
    }
}


//! [5]
void MainWindow::closeSerialPort()
{
    /* if (serialUtil->serialPort->isOpen()){
        serialUtil->serialPort->close();
        serialUtil->serial_Connect_State = false;
    }
    // console->setEnabled(false);
    //  ui->actionConnect->setEnabled(true);
    // ui->actionDisconnect->setEnabled(false);
    //   ui->actionConfigure->setEnabled(true);
    showStatusMessage("断开");*/
}

void MainWindow::showStatusMessage(QString comInfo,int hzType)
{

    if(hzType ==0){
        if(mutiSerialControl == NULL){
            statusLow->setText("接收串口状态："+comInfo);
            statusLow->setStyleSheet("background-color: red;color: rgb(255, 255, 255);font: 75 12pt 微软雅黑");
        }else{
            if(mutiSerialControl->serialPort[0]->isOpen()){
                mutiSerialControl->portStatus[0] = 1;
                statusLow->setText("接收串口状态："+comInfo);
                statusLow->setStyleSheet("background-color: rgb(0, 170, 0);color: rgb(255, 255, 255);font: 75 12pt 微软雅黑");
            }else{
                mutiSerialControl->portStatus[0] = 0;
                statusLow->setText("接收串口状态："+comInfo);
                statusLow->setStyleSheet("background-color: red;color: rgb(255, 255, 255);font: 75 12pt 微软雅黑");
            }
        }
    }else if(hzType == 1){
        if(mutiSerialControl == NULL){
            statusSend->setText("发送串口状态："+comInfo);
            statusSend->setStyleSheet("background-color: red;color: rgb(255, 255, 255);font: 75 12pt 微软雅黑");
        }else{
            if(mutiSerialControl->sendDecDataPort->isOpen()){
                mutiSerialControl->portStatus[1] = 1;
                statusSend->setText("发送串口状态："+comInfo);
                statusSend->setStyleSheet("background-color: rgb(0, 170, 0);color: rgb(255, 255, 255);font: 75 12pt 微软雅黑");
            }else{
                mutiSerialControl->portStatus[1] = 0;
                statusSend->setText("发送串口状态："+comInfo);
                statusSend->setStyleSheet("background-color: red;color: rgb(255, 255, 255);font: 75 12pt 微软雅黑");
            }
        }

    }else if(hzType == 2){
        statusTcpIp->setText("TCP状态："+comInfo);
        statusTcpIp->setStyleSheet("background-color: rgb(0, 170, 0);color: rgb(255, 255, 255);font: 75 12pt 微软雅黑");
    }else if(hzType == 3){
        statusTcpIp->setText("TCP状态："+comInfo);
        statusTcpIp->setStyleSheet("background-color: red;color: rgb(255, 255, 255);font: 75 12pt 微软雅黑");
    }

    if( mutiSerialControl->portStatus[0] == 0 || mutiSerialControl->portStatus[1] == 0){
          timerIcon->start(1000);
    }



    connect(mutiSerialControl->serialPort[0], static_cast<void (QSerialPort::*)(QSerialPort::SerialPortError)>(&QSerialPort::error),
            this, &MainWindow::handleError);

//    connect(mutiSerialControl->serialPort[1], static_cast<void (QSerialPort::*)(QSerialPort::SerialPortError)>(&QSerialPort::error),
//            this, &MainWindow::handleError1);

}

//设置 窗体主题
void MainWindow::updateUI(int theme)
{
    QPalette pal = window()->palette();
    if (theme == QChart::ChartThemeLight) {
        pal.setColor(QPalette::Window, QRgb(0xf0f0f0));
        pal.setColor(QPalette::WindowText, QRgb(0x404044));
    } else if (theme == QChart::ChartThemeDark) {
        pal.setColor(QPalette::Window, QRgb(0x121218));
        pal.setColor(QPalette::WindowText, QRgb(0xd6d6d6));
    } else if (theme == QChart::ChartThemeBlueCerulean) {
        pal.setColor(QPalette::Window, QRgb(0x40434a));
        pal.setColor(QPalette::WindowText, QRgb(0xd6d6d6));
    } else if (theme == QChart::ChartThemeBrownSand) {
        pal.setColor(QPalette::Window, QRgb(0x9e8965));
        pal.setColor(QPalette::WindowText, QRgb(0x404044));
    } else if (theme == QChart::ChartThemeBlueNcs) {
        pal.setColor(QPalette::Window, QRgb(0x018bba));
        pal.setColor(QPalette::WindowText, QRgb(0x404044));
    } else if (theme == QChart::ChartThemeHighContrast) {
        pal.setColor(QPalette::Window, QRgb(0xffab03));
        pal.setColor(QPalette::WindowText, QRgb(0x181818));
    } else if (theme == QChart::ChartThemeBlueIcy) {
        pal.setColor(QPalette::Window, QRgb(0xcee7f0));
        pal.setColor(QPalette::WindowText, QRgb(0x404044));
    } else {
        pal.setColor(QPalette::Window, QRgb(0xf0f0f0));
        pal.setColor(QPalette::WindowText, QRgb(0x404044));
    }
    window()->setPalette(pal);
}


MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::showMessage()
{
    QString titlec=tr("slot需要signal相同的参数进行传递");
    QString textc=QString::fromLocal8Bit("测试内容单击、双击、中键、按钮");
    trayIcon->showMessage(titlec, textc, QSystemTrayIcon::Information, 5000);
}

void MainWindow::showMessage(QString message)
{
    //  QString textc=QString::fromLocal8Bit(str_title);
    trayIcon->showMessage(message, str_title, QSystemTrayIcon::Information, 5000);
}

void MainWindow::iconActivated(QSystemTrayIcon::ActivationReason reason)
{
    //触发后台图标执行相应事件
    switch (reason)
    {
    case QSystemTrayIcon::Trigger:
    case QSystemTrayIcon::DoubleClick:
        showNormal();
        break;
    case QSystemTrayIcon::MiddleClick:
        showMessage("点击右键退出操作");
        break;
    default:
        break;
    }
}

void MainWindow::createActions()
{
    minimizeAction = new QAction(tr("最小化 (&I)"), this);
    connect(minimizeAction, SIGNAL(triggered()), this, SLOT(hide()));

    maximizeAction = new QAction(tr("最大化 (&X)"), this);
    connect(maximizeAction, SIGNAL(triggered()), this, SLOT(showMaximized()));

    restoreAction = new QAction(tr("还原 (&R)"), this);
    connect(restoreAction, SIGNAL(triggered()), this, SLOT(showNormal()));

    quitAction = new QAction(tr("退出 (&Q)"), this);
    connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit()));
}

void MainWindow::createTrayIcon()
{
    //设置右键点击时弹出的菜单
    trayIconMenu = new QMenu(this);
    trayIconMenu->addAction(minimizeAction);
    trayIconMenu->addAction(maximizeAction);
    trayIconMenu->addAction(restoreAction);
    trayIconMenu->addSeparator();
    trayIconMenu->addAction(quitAction);
    trayIcon->setContextMenu(trayIconMenu);
}



//关闭窗口回到导航界面
void MainWindow::closeEvent(QCloseEvent *e)
{
    //QApplication *app;
    // app->exit(0);
    hide();
    e->ignore();

}
